import router from '@/router'
import { ElMessageBox, } from 'element-plus'
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import { signature } from '@/api/common';

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      nickName: '',
      avatar: '',
      roles: [],
      permissions: [],
      // OSS信息
      ossInfo: {
        host: '',
        x_oss_date: '',
      }
    }),
    actions: {
      //获取时间戳
      getOssTime() {
        let timeStr = this.ossInfo.x_oss_date;
        let time = 0;
        if (timeStr) {
          const isoStr = timeStr.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/, "$1-$2-$3T$4:$5:$6Z");// 替换成标准的 ISO 8601 格式
          time = new Date(isoStr).getTime() + 6 * 60 * 60 * 1000; // 创建 Date 对象并获取时间戳+6天
        }
        return time;
      },
      //获取ossInfo
      async getOssInfo() {
        let time = this.getOssTime();
        //没有或者 过期
        if (!time || time < new Date().getTime()) {
          let res = await signature();
          this.ossInfo = res.data;
        }
        return this.ossInfo;
      },
      //设置ossInfo
      setOssInfo(ossInfo) {
        this.ossInfo = ossInfo
      },
      // 登录
      login(userInfo) {
        return new Promise((resolve, reject) => {
          login(userInfo).then(res => {
            let token = res.data.token;
            setToken(token)
            this.token = token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            let data = res.data;
            const user = data.user
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = data.roles
              this.permissions = data.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.userName
            this.nickName = user.nickName
            this.avatar = avatar
            /* 初始密码提示 */
            if (data.isDefaultModifyPwd) {
              ElMessageBox.confirm('您的密码还是初始密码，请修改密码！', '安全提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
              }).catch(() => { })
            }
            /* 过期密码提示 */
            if (!data.isDefaultModifyPwd && data.isPasswordExpired) {
              ElMessageBox.confirm('您的密码已过期，请尽快修改密码！', '安全提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
              }).catch(() => { })
            }
            resolve(data)
          }).catch(error => {
            reject(error)
          })
        })
      },
      //退出系统
      logOutclear() {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
        })

      },
      // 退出系统
      logOut() {
        console.log('退出系统')
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.logOutclear()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
